<template>
	<uni-popup ref="popup" type="center" :mask-click="false">
		<view class="detail-popup">
			<!-- 弹窗头部 -->
			<view class="popup-header">
				<text class="title">发票打印预览(点击图片可放大)</text>
				<uni-icons @click="close" type="close" size="20" color="#fff"></uni-icons>
			</view>

			<!-- 弹窗内容 -->
			<view class="popup-content">
				<!-- 加载中状态 -->
				<view v-if="isLoading" class="loading-container">
					<uni-icons type="spinner-cycle" size="30" color="#4a90e2"></uni-icons>
					<text class="loading-text">加载中...</text>
				</view>

				<!-- 加载失败状态 -->
				<view v-else-if="loadError" class="error-container">
					<uni-icons type="error" size="40" color="#ff4d4f"></uni-icons>
					<text class="error-text">{{ loadError }}</text>
					<button class="retry-btn" @click="renderPDF">
						<uni-icons type="refresh" size="16" color="#fff"></uni-icons>
						<text>重新加载</text>
					</button>
				</view>

				<!-- 预览图片 -->
				<image @click="handlePreviewImage" v-else-if="previewImageUrl" class="invoice-image" :src="previewImageUrl"></image>
			</view>
			<!-- 底部按钮 -->
			<view class="popup-footer">
				<button class="close-btn" @click="close">
					<uni-icons type="close" size="18" color="#fff"></uni-icons>
					<text>取消打印</text>
				</button>
				<button class="print-btn" @click="print">
					<uni-icons type="refresh-filled" size="18" color="#fff"></uni-icons>
					<text>立即打印</text>
				</button>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import * as pdfjsLib from 'pdfjs-dist';
	// 引入electron
	const { ipcRenderer } = require('electron');

	// 直接设置 worker 路径
	pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.mjs', import.meta.url).href;

	// 接收父组件传入的invoiceUrl
	const props = defineProps({
		invoiceUrl: {
			type: String,
			default: '',
		},
	});

	// 弹窗
	const popup = ref(null);

	// 默认打印机
	const defaultPrinter = ref(null);

	// 事件
	const emit = defineEmits(['printSuccess', 'close', 'print']);

	// 添加预览图片 URL 的响应式变量
	const previewImageUrl = ref('');

	// 添加加载状态和错误状态
	const isLoading = ref(false);
	const loadError = ref('');

	const handlePreviewImage = () => {
		uni.previewImage({
			urls: [previewImageUrl.value],
		});
	};

	// 打开预览
	const open = async () => {
		console.log('打开预览时的 invoiceUrl:', props.invoiceUrl);
		popup.value.open();
		await renderPDF();
	};

	// 关闭预览
	const close = () => {
		popup.value.close();
	};

	// PDF 渲染函数
	const renderPDF = async () => {
		isLoading.value = true;
		loadError.value = '';
		console.log('🚀 ~ renderPDF ~ isLoading:', isLoading.value);
		try {
			if (!props.invoiceUrl) {
				throw new Error('PDF URL 为空');
			}

			// 移除 base64 前缀
			const base64String = props.invoiceUrl.replace(/^data:application\/pdf;base64,/, '');

			if (base64String.length === 0) {
				throw new Error('PDF base64 数据为空');
			}

			// 将 base64 转换为二进制数组
			const pdfData = atob(base64String);
			const array = new Uint8Array(pdfData.length);
			for (let i = 0; i < pdfData.length; i++) {
				array[i] = pdfData.charCodeAt(i);
			}

			// 加载 PDF 文档
			const pdf = await pdfjsLib.getDocument({ data: array }).promise;
			const page = await pdf.getPage(1); // 获取第一页

			// 创建临时 canvas
			const tempCanvas = document.createElement('canvas');
			const context = tempCanvas.getContext('2d');

			// 设置适当的缩放比例和尺寸
			const scale = 2;
			const viewport = page.getViewport({ scale });
			tempCanvas.width = viewport.width;
			tempCanvas.height = viewport.height;

			// 渲染 PDF 页面到 canvas
			await page.render({
				canvasContext: context,
				viewport: viewport,
			}).promise;

			// 将 canvas 转换为图片 URL
			previewImageUrl.value = tempCanvas.toDataURL('image/png');

			// 成功后清除加载状态
			isLoading.value = false;
		} catch (error) {
			console.error('PDF 渲染错误:', error);
			loadError.value = `PDF预览失败: ${error.message}`;
			isLoading.value = false;
		}
	};

	// 处理打印
	const print = async () => {
		// 这里添加打印逻辑
		console.log('开始打印');
		const printers = await ipcRenderer.invoke('getPrinterList');
		console.log('🚀 ~ print ~ printers:', printers);

		// 如果打印机列表为空，则提示用户安装打印机
		if (!printers.length) return uni.showToast({ title: '请先安装打印机', icon: 'none' });

		// 获取默认打印机
		defaultPrinter.value = printers.find((item) => item.isDefault);

		console.log('🚀 ~ print ~ defaultPrinter:', defaultPrinter.value);

		// 生成html
		const html = `
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <style>
                @page {
                    size: A4;
                    margin: 0;
					padding: 0;
                }
                
                html, body {
                    margin: 0;
                    padding: 0;
                    width: 210mm;  /* A4 宽度 */
                    height: 297mm; /* A4 高度 */
                    background-color: white;
                }

                #print-container {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    flex-direction: column; 
                    justify-content: center;
                    align-items: center;
                    padding: 0 5mm; /* 添加左右内边距 */
                    box-sizing: border-box; /* 确保padding不会增加容器宽度 */
                }

                #printInvoiceImage {
                    width: 190mm;     /* 调整宽度，留出边距空间 */
                    height: 190mm;    /* 固定高度 */
                    object-fit: contain;  /* 保持比例，避免拉伸 */
                    margin: 0 auto;   /* 水平居中 */
					transform: rotate(90deg);
                }

                @media print {
                    html {
                        -webkit-print-color-adjust: exact;
                        print-color-adjust: exact;
                    }
                }
            </style>
        </head>
        <body>
            <div id="print-container">
                 <img id="printInvoiceImage" src="${previewImageUrl.value}" alt="发票图片">
				</div>
				</body>
				</html>
				`;
		console.log('🚀 ~ print ~ html:', html);

		console.log('🚀 ~ print ~ defaultPrinter.value:', defaultPrinter.value);

		uni.showLoading({ title: '打印中...', mask: true });

		try {
			await ipcRenderer.invoke('handlePrintInvoice', {
				silent: true,
				printBackground: true,
				color: true,
				pageSize: 'A4',
				landscape: true,
				margins: { marginType: 'custom', top: 0, bottom: 0, left: 0, right: 0 },
				deviceName: defaultPrinter.value.name,
				html: html,
				copies: 1,
				scaleFactor: 100,
			});

			ipcRenderer.on('printInvoiceCallback', (e, args) => {
				uni.hideLoading();
				// 如果回调参数存在，则提示用户打印成功
				if (args) {
					uni.showToast({ title: '打印成功', icon: 'none' });
					emit('printSuccess');
				} else uni.showToast({ title: '打印失败', icon: 'none' });
			});
		} catch (error) {
			console.log('🚀 ~ print ~ error:', error);
			uni.showToast({ title: '打印失败', icon: 'none' });
			uni.hideLoading();
		} finally {
			emit('print');
		}
	};

	// 暴露方法供父组件调用
	defineExpose({
		open,
		close,
	});

	// 修改 watch，添加更多日志
	watch(
		() => props.invoiceUrl,
		(newVal, oldVal) => {
			console.log('invoiceUrl 发生变化:', {
				新值: newVal,
				旧值: oldVal,
				长度: newVal?.length,
			});
			if (newVal) {
				renderPDF();
			} else {
				console.warn('收到空的 invoiceUrl');
			}
		},
		{ immediate: true }
	); // 添加 immediate 选项，确保组件挂载时就执行一次
</script>

<style lang="scss" scoped>
	.detail-popup {
		width: 520px;
		background: #fff;
		border-radius: 15px;

		:deep(.uni-icons) {
			font-size: 18px !important;
		}

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20px;
			background: linear-gradient(135deg, #4a90e2, #357abd);
			color: #fff;
			border-radius: 15px 15px 0 0;

			.title {
				font-size: 18px;
				font-weight: 500;
			}
		}

		.popup-content {
			padding: 20px;
			padding-bottom: 100px;
			box-sizing: border-box;
			height: 76vh;
			display: flex;
			justify-content: center;
			align-items: center;

			.invoice-image {
				width: 100%;
				height: 100%;
				object-fit: contain;
			}

			.loading-container,
			.error-container {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				gap: 15px;
			}

			.loading-text,
			.error-text {
				color: #666;
				font-size: 14px;
			}

			.retry-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 6px;
				padding: 8px 20px;
				background: linear-gradient(135deg, #4a90e2, #357abd);
				border: none;
				border-radius: 20px;
				color: #fff;
				font-size: 14px;
				cursor: pointer;
				transition: all 0.3s ease;

				&:hover {
					transform: translateY(-1px);
					box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
				}

				&:active {
					transform: translateY(0);
				}
			}

			.error-container {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				gap: 20px;
				padding: 40px;
				text-align: center;

				.error-text {
					color: #666;
					font-size: 16px;
					line-height: 1.5;
					max-width: 80%;
					margin: 0 auto;
				}

				.retry-btn {
					display: flex;
					align-items: center;
					justify-content: center;
					gap: 8px;
					padding: 12px 30px;
					background: linear-gradient(135deg, #4a90e2, #357abd);
					border: none;
					border-radius: 25px;
					color: #fff;
					font-size: 15px;
					cursor: pointer;
					transition: all 0.3s ease;
					box-shadow: 0 2px 8px rgba(74, 144, 226, 0.2);

					&:hover {
						transform: translateY(-2px);
						box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
					}

					&:active {
						transform: translateY(0);
						box-shadow: 0 2px 6px rgba(74, 144, 226, 0.2);
					}
				}
			}
		}
		.popup-footer {
			padding: 15px;
			text-align: center;
			background: #f8f8f8;
			border-top: 1px solid #eee;
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			border-radius: 0 0 15px 15px;
			display: flex;
			gap: 15px;
			justify-content: center;

			.close-btn,
			.print-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0 30px;
				height: 38px;
				font-size: 14px;
				border: none;
				width: 220px;
				border-radius: 24px;
				transition: all 0.3s ease;
				gap: 6px;

				&:hover {
					transform: translateY(-1px);
				}

				&:active {
					transform: translateY(0);
				}
			}

			.close-btn {
				color: #fff;
				background: linear-gradient(135deg, #606c88, #3f4c6b);
				box-shadow: 0 2px 6px rgba(74, 144, 226, 0.2);

				&:hover {
					box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
				}
			}

			.print-btn {
				color: #fff;
				background: linear-gradient(135deg, #ff4d4f, #ff7875);
				box-shadow: 0 2px 6px rgba(255, 77, 79, 0.2);

				&:hover {
					box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
				}
			}
		}
	}
</style>
